const layer = layui.layer
const form = layui.form
$(function () {


    initArtCateList()
})
function initArtCateList() {
    $.ajax({
        method: 'GET',
        url: '/my/article/cates',
        success: function (res) {
            // console.log(res);
            var htmlStr = template('tpl-table', res)
            $('tbody').html(htmlStr)
        }
    })
}
let indexAdd;
$('#btnAddCate').on('click', function () {
    indexAdd = layer.open({
        type: 1,
        area: ['500px', '250px'],
        title: '添加文章分类',
        content: $('#dialog-add').html()
    })
})
$('body').on('submit', '#form-add', function (e) {
    e.preventDefault()
    $.ajax({
        method: 'POST',
        url: '/my/article/addcates',
        data: $(this).serialize(),
        success: function (res) {
            if (res.status !== 0) {
                return layer.msg('新增分类失败！')
            }
            initArtCateList()
            layer.msg('新增分类成功！')
            // 根据索引，关闭对应的弹出层
            layer.close(indexAdd)
        }
    })
})
let indexEdi;
$('body').on('click', '.btn-edit', function (e) {

    indexEdi = layer.open({
        type: 1,
        area: ['500px', '250px'],
        title: '添加文章分类',
        content: $('#dialog-edit').html()
    });
    const id = $(this).attr('data-id')
    // 发起请求获取对应分类的数据
    $.ajax({
        method: 'GET',
        url: '/my/article/cates/' + id,
        success: function (res) {

            form.val('form-edit', res.data)
        }
    })
})
// 修改
$('body').on('submit', '#form-edit', function (e) {
    e.preventDefault();
    $.ajax({
        method: 'POST',
        url: '/my/article/updatecate',
        data: $(this).serialize(),
        success: function (res) {
            if (res.status !== 0) return layer.msg('更新分类数据失败');
            layer.msg('更新分类数据失败')
            layer.close(indexEdi)
            initArtCateList()
        }
    })
})
// 删除
$('body').on('click', '.del_btn', function () {
    const id = $(this).attr('data-id')
    layer.confirm('确认删除?', { icon: 3, title: '提示' }, function (index) {
        $.ajax({
            type: 'get',
            url: '/my/article/deletecate/' + id,
            success: function (res) {
                // console.log(res);
                if (res.status !== 0) {
                    return layer.msg('删除分类失败！')
                }
                layer.msg('删除分类成功！')
                layer.close(index)
                initArtCateList()
            }
        })
    })
})